﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DataAccessLib;
using System.Linq;

namespace ePharmacyLauch
{
    public partial class DmGoi : BaseForm
    {
        private NhaThuocModelDataContext context = new NhaThuocModelDataContext();
        private DataTable table1;
        private DataTable table2;
        public DmGoi()
        {
            InitializeComponent();
        }

        private void InitTable2() {
            this.table2 = new DataTable("tb2");
            this.table2.Columns.Add("Chon", typeof(bool));
            this.table2.Columns.Add("MaThuoc", typeof(int));
            this.table2.Columns.Add("TenThuoc", typeof(string));
            this.table2.Columns.Add("MoTa", typeof(string));
            this.table2.Columns.Add("DonVi", typeof(string));
        }

        private void InitTable1() {
            this.table1 = new DataTable("tb1");
            this.table1.Columns.Add("MaThuoc", typeof(int));
            this.table1.Columns.Add("TenThuoc", typeof(string));
            this.table1.Columns.Add("MoTa", typeof(string));
            this.table1.Columns.Add("DonVi", typeof(string));
            this.table1.Columns.Add("SoLuong", typeof(decimal));
            this.table1.Columns.Add("DonGia", typeof(decimal));

        }

        private void DmGoi_Load(object sender, EventArgs e)
        {
            InitTable2();
            InitTable1();

            //init dvt
            var dvt = this.context.DonVis.ToList();
            foreach (var i in dvt) 
            {
                repComboDVT2.Items.Add(i.TenDonVi);
                repComboDVT1.Items.Add(i.TenDonVi);
            }
            
            //load ten goi
            this.teTenGoi.Properties.AutoComplete = true;
            this.teTenGoi.Properties.DropDownRows = 20;
            this.teTenGoi.Properties.ImmediatePopup = true;
            var goiList = (from g in context.GoiThuocs where g.Dung select g.TenGoi).ToList();
            foreach (var g in goiList) {
                this.teTenGoi.Properties.Items.Add(g);
            }
            //==============load danh sahc thuoc
            var thuocList = (from t in context.Thuocs
                            join dv in context.DonVis on t.DVT equals dv.Id
                            where t.Dung == true
                            select new
                            {
                                MaThuoc = t.Id,
                                TenThuoc = t.TenThuoc,
                                MoTa = t.MoTa,
                                DonVi = dv.TenDonVi
                            }).ToList();
            for (int i = 0; i < thuocList.Count; i++)
            {
                var th = thuocList[i];
                var r = this.table2.NewRow();
                r.ItemArray = new object[] { 
                    false, th.MaThuoc, th.TenThuoc, th.MoTa, th.DonVi
                };
                this.table2.Rows.Add(r);
            }
            this.table2.AcceptChanges();
            this.gridControl2.DataSource = table2;

            //========== goi thuoc
            this.gridControl1.DataSource = table1;


        }

        private string IsExistInTable1(int maThuoc) {
            foreach (DataRow r in this.table1.Rows) {
                if (int.Parse(r["MaThuoc"].ToString()) == maThuoc)
                    return r["TenThuoc"].ToString();
            }
            return string.Empty;
        }

        private void DoInsert() {
            string message = string.Empty;
            foreach (DataRow r in this.table2.Rows) {
                if (r.RowState == DataRowState.Modified) {
                    var exist = IsExistInTable1(int.Parse(r["MaThuoc"].ToString()));
                    if (exist != string.Empty)
                    {
                        message += exist + ",";
                        continue; 
                    }
                    var rr = this.table1.NewRow();
                    rr.ItemArray = new object[] { 
                        r["MaThuoc"], r["TenThuoc"], r["MoTa"], r["DonVi"], 0d, 0d
                    };

                    this.table1.Rows.Add(rr);
                }
            }
            this.table1.AcceptChanges();

            this.table2.RejectChanges();
            if (message != string.Empty){
                MessageBox.Show(message.Trim(','), "Các loại thuốc sau đây đã được thêm vào gói");
            }
        }

        private bool DoSave() 
        {
            try
            {
                var goithuoc = (from g in this.context.GoiThuocs
                                where g.Dung && g.TenGoi == this.teTenGoi.Text.Trim()
                                select g).ToList().FirstOrDefault();
                if (goithuoc != null) {
                    return DoUpdate(goithuoc);
                }
                
                //save goi thuoc
                var goithuocNew = new GoiThuoc
                {
                    TenGoi = this.teTenGoi.Text.Trim(),
                    MoTa = this.mmGhiChu.Text.Trim(),
                    Gia = decimal.Parse(this.teSoTien.Text),
                    Dung = true
                };
                this.context.GoiThuocs.InsertOnSubmit(goithuocNew);
                this.context.SubmitChanges();
                var maGoiThuoc = goithuocNew.Id;

                //save chi tiet goi thuoc
                foreach (DataRow r in this.table1.Rows)
                {
                    var ctGoiThuoc = new CTGoiThuoc
                    {
                        MaGoiThuoc = maGoiThuoc,
                        MaThuoc = Convert.ToInt32(r["MaThuoc"].ToString()),
                        MaDonVi = GetMaDonVi(r["DonVi"].ToString()),
                        SoLuong = Convert.ToDecimal(r["SoLuong"].ToString())

                    };
                    this.context.CTGoiThuocs.InsertOnSubmit(ctGoiThuoc);
                }
                this.context.SubmitChanges();
            }
            catch (Exception ex)
            {
                return false;
            }

            return true;
        }

        private bool DoUpdate(GoiThuoc goithuoc)
        {
            //update goi thuoc
            try
            {
                goithuoc.MoTa = this.mmGhiChu.Text.Trim();
                goithuoc.Dung = true;

                this.context.SubmitChanges();

                //delete al chitietgoi
                var ctgoiList = (from ct in this.context.CTGoiThuocs where ct.MaGoiThuoc == goithuoc.Id select ct).ToList();
                if (ctgoiList != null && ctgoiList.Count > 0) {
                    foreach (var ctgoi in ctgoiList)
                        this.context.CTGoiThuocs.DeleteOnSubmit(ctgoi);
                }
                this.context.SubmitChanges();

                //
                foreach (DataRow r in this.table1.Rows)
                {
                    var ctGoiThuoc = new CTGoiThuoc
                    {
                        MaGoiThuoc = goithuoc.Id,
                        MaThuoc = Convert.ToInt32(r["MaThuoc"].ToString()),
                        MaDonVi = GetMaDonVi(r["DonVi"].ToString()),
                        SoLuong = Convert.ToDecimal(r["SoLuong"].ToString()),
                        
                        
                    };
                    this.context.CTGoiThuocs.InsertOnSubmit(ctGoiThuoc);
                }
                this.context.SubmitChanges();

                return true;
               
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.ToString());
                return false;
            }
            return true;
        }

        private void ucBtChon_Click(object sender, EventArgs e)
        {
            DoInsert();
        }

        private void ucBtSave_Click(object sender, EventArgs e)
        {
            try
            {
                bool bResult = true;
                bResult = DoSave();
                if (!bResult)
                {
                    MessageBox.Show("Lưu dữ liệu không thành công!");
                }
                else
                {
                    MessageBox.Show("Lưu dữ liệu thành công!");
                    DoCleanup();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return;
            }
            
        }

        private void DoCleanup()
        {
            this.table1.Rows.Clear();
            this.gridControl1.DataSource = table1;

            this.teTenGoi.Text = string.Empty;
            //refresh teTenGoi
            var goiList = (from g in this.context.GoiThuocs where g.Dung select g.TenGoi).ToList();
            this.teTenGoi.Properties.Items.Clear();
            foreach (var goi in goiList) teTenGoi.Properties.Items.Add(goi);
            this.teSoTien.Text = string.Empty;

        }

        private void mmGhiChu_Properties_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void cbMaThuoc_Properties_Leave(object sender, EventArgs e)
        {

        }

        private void cbMaThuoc_Properties_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter) {
                var comboBox = (ComboBoxEdit)sender;
                if (comboBox.Text.Trim() != string.Empty) {
                    var first = this.context.GoiThuocs.FirstOrDefault(x => x.TenGoi == comboBox.Text.Trim());
                    if (first != null) {
                        var ctGoiList = (from ct in this.context.CTGoiThuocs
                                         join t in this.context.Thuocs on ct.MaThuoc equals t.Id
                                         join dv in this.context.DonVis on ct.MaDonVi equals dv.Id
                                         where ct.MaGoiThuoc == first.Id
                                         select new { 
                                            MaThuoc = ct.MaThuoc,
                                            TenThuoc = t.TenThuoc,
                                            MoTa = t.MoTa,
                                            DonVi = dv.TenDonVi,
                                            SoLuong = ct.SoLuong
                                            //DonGia = ct.DonGia
                                         }).ToList();

                        teSoTien.Text = first.Gia.ToString ();
                        mmGhiChu.Text = first.MoTa.ToString ();
                        laID.Text = first.Id.ToString ();
                        if (ctGoiList != null)
                        {
                            foreach (var ctgoi in ctGoiList) {
                                var r = this.table1.NewRow();
                                r.ItemArray = new object[] { 
                                   ctgoi.MaThuoc, ctgoi.TenThuoc, ctgoi.MoTa, ctgoi.DonVi, ctgoi.SoLuong
                                };
                                this.table1.Rows.Add(r);
                            }
                            this.table1.AcceptChanges();
                        }
                    }

                    return;
                }
                MessageBox.Show("Xin nhập tên gói");
            }
        }
        //cap nhat danh muc goi thuoc
        private void ucBtUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                bool flag = true;
                flag = DoDeleteHeader();
                if (flag == false)
                {
                    MessageBox.Show("Xóa dữ liệu không thành công");
                    return;
                }
                //else
                //{
                //    MessageBox.Show("Xóa dữ liệu thành công");
                //        gridControl1.RefreshDataSource();
                //}
                flag = DoDeleteLine(); 
                if (flag == false)
                {
                    MessageBox.Show("Xóa dữ liệu không thành công");
                    return;
                }
                MessageBox.Show("Xóa dữ liệu thành công");
                gridControl1.RefreshDataSource();


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        private bool DoDeleteHeader() 
        {
            try
            {
                //if (this.table1 == null || this.table1.Rows.Count == 0)
                //{
                //    MessageBox.Show("Đơn hàng rỗng");
                //    return false;
                //}

                //this.gridView1.DeleteSelectedRows();

                var gt = this.context.GoiThuocs.First(x => x.Id.ToString() == laID.Text);
                if (gt != null)
                    this.context.GoiThuocs.DeleteOnSubmit(gt);
                this.context.SubmitChanges();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return false;
            }
            return true; 
        }

        private bool DoDeleteLine()
        {
            try
            {
                //if (this.table1 == null || this.table1.Rows.Count == 0)
                //{
                //    MessageBox.Show("Đơn hàng rỗng");
                //    return false;
                //}

                //this.gridView1.DeleteSelectedRows();

                var ctgt = this.context.CTGoiThuocs.First(x => x.Id.ToString() == laID.Text);
                if (ctgt != null)
                    this.context.CTGoiThuocs.DeleteOnSubmit(ctgt);
                this.context.SubmitChanges();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return false;
            }
            return true;
        }

        private int GetMaDonVi(string tenDv)
        {
            var first = this.context.DonVis.FirstOrDefault(x => x.TenDonVi == tenDv);
            if (first != null)
                return first.Id;

            return 0;
        }

    }
}